package com.chaoyong.higo.activity;

import org.apache.http.entity.StringEntity;
import org.json.JSONException;
import org.json.JSONObject;

import com.chaoyong.higo.R;
import com.chaoyong.higo.base.BaseActivity;
import com.chaoyong.higo.net.OApi;
import com.chaoyong.higo.utils.AtyManager;
import com.chaoyong.higo.utils.EmptyUtil;
import com.chaoyong.higo.utils.JLog;
import com.chaoyong.higo.utils.MyCountTimer;
import com.chaoyong.higo.utils.StringUtils;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;

import android.content.Intent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

/**
 * 登录
 * 
 * @author zk
 *
 */
public class RegisterActivity extends BaseActivity {

	private static final String ClassName = RegisterActivity.class.getName();

	private LinearLayout base_left_iv;// 左侧返回按钮
	private TextView base_title_tv;// 标题
	private TextView base_right_tv;// 标题右侧文字

	/** 手机号 */
	private EditText reg_phone;
	/** 密码 */
	private EditText reg_pwd;
	/** 验证码 */
	private EditText reg_code;
	/** 获取验证码 */
	private TextView reg_get_code;
	/** 是否同意协议 */
	private ImageView reg_select;
	/** 服务协议 */
	private TextView reg_service;
	/** 注册按钮 */
	private Button reg_register;

	private MyCountTimer timer;

	private boolean isAgree = false;

	@Override
	public int layoutResID() {
		return R.layout.activity_register;
	}

	@Override
	public void findView() {
		findTitleIds();

		reg_phone = (EditText) findViewById(R.id.reg_phone);
		reg_pwd = (EditText) findViewById(R.id.reg_pwd);
		reg_code = (EditText) findViewById(R.id.reg_code);
		reg_get_code = (TextView) findViewById(R.id.reg_get_code);
		reg_service = (TextView) findViewById(R.id.reg_service);
		reg_select = (ImageView) findViewById(R.id.reg_select);
		reg_register = (Button) findViewById(R.id.reg_register);
	}

	@Override
	public void init() {
		AtyManager.getAtyManager().addActivity(RegisterActivity.this);

		base_left_iv.setOnClickListener(this);
		base_right_tv.setOnClickListener(this);
		reg_get_code.setOnClickListener(this);
		reg_select.setOnClickListener(this);
		reg_service.setOnClickListener(this);
		reg_register.setOnClickListener(this);

		timer = new MyCountTimer(reg_get_code, 0xfff30008, 0xff969696);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.base_left_iv:// 返回
			this.finish();
			break;
		case R.id.base_right_tv:// 右上角-注册
			// startActivity(new Intent(this, LoginActivity.class));
			this.finish();
			break;
		case R.id.reg_get_code:// 获取验证码
			if (!StringUtils.isEmpty(getText(reg_phone))) {
				//timer.start();
				httpGetCodes(getText(reg_phone));
			} else {
				showToast("请输入手机号");
			}
			break;
		case R.id.reg_select:// 是否同意协议
			if (isAgree) {
				reg_select.setBackgroundResource(R.drawable.dui1);
				isAgree = false;
			} else {
				reg_select.setBackgroundResource(R.drawable.dui2);
				isAgree = true;
			}
			break;
		case R.id.reg_service:// 协议
			startActivity(new Intent(this, XieyiActivity.class));
			break;
		case R.id.reg_register:// 注册按钮
			if (beforeCommit()) {
				return;
			} else {
				if (isAgree) {
					httpRegister(getText(reg_phone), getText(reg_pwd), getText(reg_code));
				} else {
					reg_service.setError("请同意协议");
					showToast("请同意协议");
				}
			}
			break;
		}
	}

	/**
	 * 初始化title部分的控件
	 */
	private void findTitleIds() {
		base_left_iv = (LinearLayout) findViewById(R.id.base_left_iv);
		base_title_tv = (TextView) findViewById(R.id.base_title_tv);
		base_right_tv = (TextView) findViewById(R.id.base_right_tv);

		base_title_tv.setText("注册");
		base_right_tv.setText("登录");
	}

	/**
	 * 获取editText输入的内容
	 * 
	 * @param et
	 * @return
	 */
	private String getText(EditText et) {
		return et.getText().toString().trim();
	}

	/**
	 * 检查输入是否为空
	 * 
	 * @return
	 */
	private boolean beforeCommit() {
		if (EmptyUtil.isEmpty(getText(reg_phone)) || reg_phone.getText().length() < 11) {
			reg_phone.setError("请输入正确的手机号", getResources().getDrawable(R.color.back_color));
			reg_phone.requestFocus();
			return true;
		}

		if (EmptyUtil.isEmpty(getText(reg_pwd))
				|| (reg_pwd.getText().length() > 20 && reg_pwd.getText().length() < 8)) {
			reg_pwd.setError("请输入合法密码，（字母、数字、下划线）");
			reg_pwd.requestFocus();
			return true;
		}

		if (EmptyUtil.isEmpty(getText(reg_code))) {
			reg_code.setError("验证码不能为空");
			reg_code.requestFocus();
			return true;
		}

		return false;
	}

	/** 获取验证码 */
	private void httpGetCodes(String phoneNum) {
		HttpUtils utils = new HttpUtils();
		RequestParams param = new RequestParams();
		try {
			JSONObject jsonObject = new JSONObject();
			jsonObject.putOpt("username", phoneNum);
			param.setBodyEntity(new StringEntity(jsonObject.toString(), "UTF-8"));
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		utils.send(HttpMethod.POST, OApi.Appport_index, param, new RequestCallBack<String>() {

			@Override
			public void onFailure(HttpException arg0, String arg1) {
				JLog.i(ClassName, arg0.getMessage());
			}

			@Override
			public void onSuccess(ResponseInfo<String> arg0) {
				JLog.i(ClassName, arg0.result);
				try {
					JSONObject o = new JSONObject(arg0.result);
					String data = o.getString("data");
					showToast(data);
					if(o.getInt("status") == 1){
						timer.start();
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}

		});
	}

	/**
	 * 注册
	 * 
	 * @param phone
	 *            手机号
	 * @param pwd
	 *            密码
	 * @param code
	 *            验证码
	 */
	private void httpRegister(String phone, String pwd, String code) {
		HttpUtils utils = new HttpUtils();
		RequestParams param = new RequestParams();
		try {
			JSONObject jsonObject = new JSONObject();
			jsonObject.putOpt("username", phone);
			jsonObject.putOpt("code", code);
			jsonObject.putOpt("password", pwd);
			param.setBodyEntity(new StringEntity(jsonObject.toString(), "UTF-8"));
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		utils.send(HttpMethod.POST, OApi.Appport_index, param, new RequestCallBack<String>() {

			@Override
			public void onFailure(HttpException arg0, String arg1) {
				JLog.i(ClassName, arg0.getMessage());
			}

			@Override
			public void onSuccess(ResponseInfo<String> arg0) {
				String result = arg0.result;
				try {
					JSONObject o = new JSONObject(arg0.result);
					String data = o.getString("data");
					String status = o.getString("status");
					if (status.equals("1")) {
						// 注册成功之后，带参跳转到登录页面
						Intent toLoagin = new Intent(RegisterActivity.this, LoginActivity.class);
						toLoagin.putExtra("ph", getText(reg_phone));
						toLoagin.putExtra("pw", getText(reg_pwd));
						startActivity(toLoagin);
						showToast("注册成功，请登录");
					}
					//showToast(data);
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}
		});
	}

}
